import { defineStore } from 'pinia'
import request from '../utils/request'
import { login, logout, register } from '@/api/auth.js'

const secretKey = 'alvin'
export const useAuthStore = defineStore('auth', {
  state: () => ({
    accessToken: null,
    refreshToken: null,
    user: null,
    tempRegisterInfo: null
  }),
  persist:{
    storage: localStorage,
    key:'auth_info'
  },
  getters: {
    isAuthenticated: (state) => !!state.user
  },
  actions: {
    async login(username, password) {
      try {
        const response = await login(username, password)

        if (response.data) {
          const data = response.data
          this.setUser(data.user)
          this.setAccessToken(data.access_token)
          this.setRefreshToken(data.refresh_token)

          console.log(data.user)
          // localStorage.setItem('alvin-user', JSON.stringify(this.user))
          // request.defaults.headers.common['Authorization'] = `Bearer ${this.token}`
          return { success: true, message: '登录成功！' }
        }
        return { success: false, message: response.message }

      } catch (error) {
        // console.log(error.response)
        console.error('Login failed', error)
        return { success: false, message: error.response.data.message }
      }
    },
    async register(userData) {
      try {
        const response = await register(userData)
        console.log(response)
        if (response.status_code === 200) {
          // 注册成功，但通常不会立即登录用户
          // 如果您想在注册后立即登录用户，可以在这里调用 this.login
          return { success: true, message: '注册成功！' }
        } else {
          return { success: false, message: response.message }
        }
      } catch (error) {
        console.error('Registration failed', error)
        return { success: false, message: error.response?.data?.message || '注册失败' }
      }
    },
    async logout() {
      const response = await logout()
      this.clearAuth()
    },
    setUser(user) {
      this.user = user
    },
    clearAuth() {
      this.user = null
      this.accessToken = null
      this.refreshToken = null
    },
    setTempRegisterInfo(info) {
      this.tempRegisterInfo = info
    },
    clearTempRegisterInfo() {
      this.tempRegisterInfo = null
    },
    setAccessToken(token) {
      // 在state中添加accessToken
      this.accessToken = token
    },
    setRefreshToken(token) {
      // 在state中添加accessToken
      this.refreshToken = token
    },
    async fetchProtectedData() {
      try {
        const response = await request({
          url: '/protected',
          method: 'get'
        })
        return response
      } catch (error) {
        console.error('Failed to fetch protected data', error)
      }
    }
  }
})
